using System;
using System.Linq;
using UnityEngine;
using WolfCarol.AvgToolkit.Command;
using WolfCarol.AvgToolkit.Save;

namespace WolfCarol.AvgToolkit.Examples
{
    public class Branch : ChoicePresenter, ISavable<ChoiceData[]>
    {
        [SerializeField] private ChoiceButton[] m_choices;

        public CommandManager commandManager;

        private void Awake()
        {
            for (int i = 0; i < m_choices.Length; i++)
            {
                m_choices[i].SetChoicePresenter(this);
            }
        }

        public override void OnChoiceButtonDown(string flag)
        {
            Clear();
            commandManager.Choose(flag);
        }

        public override void PresentChoice(string flag, string dialogue)
        {
            for (int i = 0; i < m_choices.Length; i++)
            {
                if (m_choices[i].gameObject.activeSelf == false)
                {
                    m_choices[i].SetChoice(dialogue, flag);
                    m_choices[i].gameObject.SetActive(true);
                    return;
                }
            }

            throw new Exception($"Choice count could not over {m_choices.Length}.");
        }

        public void Clear()
        {
            for (int i = 0; i < m_choices.Length; i++)
            {
                m_choices[i].Clear();
            }
        }

        public ChoiceData[] Save()
        {
            return m_choices.Select(choice => choice.Save()).ToArray();
        }

        public void Load(ChoiceData[] obj)
        {
            for (int i = 0; i < obj.Length; i++)
            {
                m_choices[i].Load(obj[i]);
            }
        }
    }
}
